<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
</head>

<body>
  <div id="app">
    <post-list></post-list>
  </div>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script>
    const app = Vue.createApp({});
    // 父组件
    app.component('PostList', {
      data() {
        return {
          posts: [
            { id: 1001, title: '洗衣机', author: '海尔', date: '2022-10-21', vote: 1000 },
            { id: 1002, title: '冰箱', author: '美的', date: '2022-10-21', vote: 1220 },
            { id: 1003, title: '电视机', author: '创维', date: '2022-10-22', vote: 1230 },
            { id: 1004, title: '电脑', author: '戴尔', date: '2022-11-23', vote: 1300 },
          ]
        }
      },
      methods: {
        // 自定义事件vote的事件处理器方法
        handleVote(id) {
          this.posts = this.posts.map(item =>
            item.id === id ? { ...item, vote: item.vote + 1 } : item
          );
        }
      },
      render() {
        let postNodes = [];
        // this.posts.map取代v-for指令， 循环遍历posts,
        // 构造子组件的虚拟节点
        this.posts.map(post => {
          let node = Vue.h(Vue.resolveComponent('PostListItem'), {
            post: post,
            onVote: () => this.handleVote(post.id)
          });
          postNodes.push(node);
        })
        return Vue.h('div', [
          Vue.h('ul', [
            postNodes
          ])
        ])
      }
    })
    // 子组件
    app.component('PostListItem', {
      props: {
        post: {
          type: Object,
          required: true
        }
      },
      render() {
        return Vue.h('li', [
          // 这是<span>元素的内容
          Vue.h('span', '编号：' + this.post.id + '| 商品名称： ' + this.post.title + ' | 品牌：' + this.post.author + ' | 采购时间：' + this.post.date + ' | 采购数量： ' + this.post.vote),
          Vue.h('button', { onClick: () => this.$emit('vote') }, '增加采购数量')
        ],

        )
      }
    });
    app.mount('#app');
  </script>
</body>

</html>